<template>
  <div class="tree-check-box">
    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="treeData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
      />
      <div class="tree-btn">
        <el-button size="medium" type="warning" plain @click="$emit('closeDialog')">取消</el-button>
        <el-button size="medium" type="primary" plain @click="onSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getPermissionRequest } from '@/api/permission'
import { getUserPermissionByIdRequest, updateAssignPermissionByIdRequest } from '@/api/user'
import { transformListToTree2 } from '@/utils'
export default {
  props: {
    // 接收父组件传递的当前项数据的 id
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 树形结构数据
      treeData: [],
      // 树形结构绑定的数据
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getPermission() // 获取角色详情
  },
  methods: {
    // ^ ==================== 请求 ====================
    // 请求 - 获取所有权限点列表
    async getPermission() {
      try {
        const res = await getPermissionRequest(this.currentId)
        if (res.success) {
          // console.log('获取所有权限点列表成功', res.data.rows)
          // 调用函数, 通过递归将平面数据转为树形结构
          this.treeData = transformListToTree2(res.data, '0')
        } else {
          this.$message.error(res.resmessage || '获取所有权限点列表失败')
        }
        // 根据 ID 获取角色详情
        const res2 = await getUserPermissionByIdRequest(this.currentId)
        if (res2.success) {
          // 数据回显
          this.$refs.treeRef.setCheckedKeys(res2.data?.permIds || []) // 逻辑中断与兼容处理
        } else {
          this.$message.error(res2.resmessage || '获取角色详情失败')
        }
      } catch (error) {
        console.log('获取所有权限点列表失败', error)
      }
    },
    // 请求 - 给角色分配权限
    async updateAssignPermissionById() {
      try {
        const res = await updateAssignPermissionByIdRequest({
          id: this.currentId,
          permIds: this.$refs.treeRef.getCheckedKeys()
        })
        if (res.success) {
          this.$message.success('分配权限成功!')
        } else {
          this.$message.error(res.message || '分配角色权限失败!')
        }
      } catch (error) {
        console.log('分配权限失败', error)
      }
    },

    // ^ ==================== 事件 ====================
    onSubmit() {
      this.updateAssignPermissionById() // 给角色分配权限
      this.$emit('closeDialog')
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-btn {
  text-align: right;
  margin-top: 25px;
}
</style>
